<template>
  <el-form
    size="mini"
    :model="userFormData"
    status-icon
    :rules="rules"
    ref="userFormRef"
    label-width="90px"
  >
    <el-form-item label="姓名" prop="realname">
      <el-input type="text" v-model="userFormData.realname" autocomplete="off"></el-input>
      <span class="el-icon-warning-outline tip" v-if="!errorFields.includes('realname')">
        姓名为身份证中的名称</span
      >
    </el-form-item>
    <el-form-item label="账号" prop="username">
      <el-input type="text" v-model="userFormData.username" autocomplete="off"></el-input>
      <span class="el-icon-warning-outline tip" v-if="!errorFields.includes('username')">
        账号要为全英文字母或数字组成</span
      >
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="text" v-model="userFormData.password" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="角色" prop="role">
      <el-select v-model="userFormData.role" filterable placeholder="请选择角色">
        <el-option v-for="item in roles" :key="item.id" :label="item.cname" :value="item.id">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="性别" prop="sex">
      <el-radio-group v-model="userFormData.sex">
        <el-radio label="1">先生</el-radio>
        <el-radio label="2">女士</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="手机" prop="phone">
      <el-input type="text" v-model="userFormData.phone" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="生日" prop="birthday">
      <el-date-picker
        type="date"
        placeholder="选择日期"
        value-format="yyyy-MM-dd"
        v-model="userFormData.birthday"
      />
    </el-form-item>
    <el-form-item label="头像">
      <!-- 
        action必填string,图片上传的url地址
      -->
      <el-upload
        class="avatar-uploader"
        :action="uploadActionUrl"
        :multiple="false"
        :show-file-list="false"
        accept=".jpg,.jpeg,.gif,.png"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="imgUrl" :src="imgUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png/gif文件，且不超过1MB</div>
      </el-upload>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('userFormRef')">提交</el-button>
      <el-button @click="resetForm('userFormRef')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getFullYearDay } from '@/utils/tools'
import { addUserApi, uploadAvatarApi } from '@/api/userApi'
import { rolesApi } from '@/api/roleApi'
import { addUserRulesMixin } from '../mixin'
export default {
  mixins: [addUserRulesMixin],
  props: ['setDialogVisible'],
  data() {
    return {
      imgUrl: '',
      roles: [],
      userFormData: {
        realname: '',
        username: '',
        password: '',
        sex: '1',
        phone: '13521512512',
        birthday: getFullYearDay(-20)[0],
        avatar: '',
        role: ''
      }
    }
  },
  computed: {
    uploadActionUrl() {
      // return process.env.VUE_APP_APIHOST + '/api/user/uploadAvatar'
      return ''
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    async loadRoles() {
      let ret = await rolesApi(1, 999)
      this.roles = ret.data.roles
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid, errors) => {
        this.errorFields = Object.keys(errors)
        if (valid) {
          // 发送网络请求给后端接口
          console.log(this.userFormData)
          let ret = await addUserApi(this.userFormData)
          // 新增用户成功
          if (ret.code === 0) {
            this.$message({
              message: '新增用户成功！',
              type: 'success',
              showClose: true,
              duration: 3000,
              onClose: () => {
                // 关才弹出层之前，需要对表单项进行清空操作
                this.resetForm(formName)
                // 添加成功后，后端接口返回数据后，关闭当前弹出层
                this.setDialogVisible(false)
              }
            })
          } else {
            // 提示一下
            this.$message({
              message: '新增用户失败，请认真检查填写的内容！',
              type: 'error',
              duration: 3000
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 在上传之前完成对于文件类型的限制和大小的限制
    // true继续上传,false中止
    async beforeAvatarUpload(file) {
      // 限制当前上传的文件它的大小只能为1mb
      // file.size 当前文件的字节 byte kb mb  1024/1024
      const isSize = file.size <= 1024 * 1024
      if (!isSize) {
        this.$alert('当前上传的头像过大,超过1MB', { showClose: true })
        return false
      }

      // 限制当前上传的文件它只能是图片
      let allowImage = ['image/jpeg', 'image/gif', 'image/png']
      const isType = allowImage.includes(file.type)
      if (!isType) {
        this.$alert('当前上传的头像是一个不合法的文件,只能上传图片', {
          showClose: true
        })
        return false
      }

      // 限制上传的文件的长宽比例
      const img = new Image()
      img.src = window.URL.createObjectURL(file)
      const h = img.naturalHeight
      const w = img.naturalWidth
      if ((h >= 100) & (h <= 300) || (w >= 60 && w <= 600)) {
        this.$alert('当前上传的图片长或宽不符合上传的尺寸要求', {
          showClose: true
        })
        return false
      }

      // 调用定义的上传方法完成上传 FormData
      const formData = new FormData()
      formData.append('file', file)
      let ret = await uploadAvatarApi(formData)
      if (ret.code == 0) {
        this.imgUrl = ret.data.url
        this.userFormData.avatar = ret.data.filepath
      }
      return false
    },
    // response它就是上传成功后,服务器返回过来的数据
    handleAvatarSuccess(response) {
      if (response.code == 0) {
        this.imgUrl = response.data.url
        this.userFormData.avatar = response.data.filepath
      }
    }
  }
}
</script>

<style lang="scss" scoped>
$wh: 100px;
.tip {
  color: #c0c4cc;
  font-size: 12px;
}
:deep(.avatar-uploader) {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload:hover {
    border-color: #409eff;
  }
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: $wh;
  height: $wh;
  line-height: $wh;
  text-align: center;
}
.avatar {
  width: $wh;
  height: $wh;
  display: block;
}
</style>
